﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using AccompanyCabinet.Model;
using System.Net;
using AccompanyCabinet.Interface;
using AccompanyCabinet.Front;
using System.Windows.Forms;

namespace AccompanyCabinet.Common
{
    public class VideoHelper
    {

        private readonly IMessageProvider _MessageProvider;
        public  VideoHelper(IMessageProvider messageProvider)
        {
            _MessageProvider = messageProvider;
        }

        /// <summary>
        /// 视频缓存文件目录
        /// </summary>
        public static string VideoCacheFileDirectory
        {
            get
            {
                string directory = ConfigurationManager.AppSettings["VideoCacheFileDirectory"];
                if(!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }
                return directory;
            }
        }

        /// <summary>
        /// Signalr服务器地址
        /// </summary>
        public static string SignalrServerAddress
        {
            get
            {
                return ConfigurationManager.AppSettings["SignalrServerAddress"];
            }
        }
        /// <summary>
        /// 视频文件下载地址
        /// </summary>
        public static string VideoDownloadAddress
        {
            get
            {
                return ConfigurationManager.AppSettings["VideoDownloadAddress"];
            }
        }
        /// <summary>
        ///视频列表地址
        /// </summary>
        public static string VideoListAddress
        {
            get
            {
                return ConfigurationManager.AppSettings["VideoListAddress"];
            }
        }
        /// <summary>
        /// 视频下载分区大小
        /// </summary>
        public static ulong VideoDownPartionSize
        {
            get
            {
                ulong partionSize =102400;//默认100k
                ulong.TryParse(ConfigurationManager.AppSettings["VideoDownPartionSize"],out partionSize);
                return partionSize;
            }
        }

        /// <summary>
        /// 获取本地视频缓存文件
        /// </summary>
        public string[] LocalVideoCacheFiles
        {
            get
            {
                if(string.IsNullOrEmpty(VideoCacheFileDirectory))
                {
                    return new string[0];
                }
                return Directory.GetFiles(VideoCacheFileDirectory);
            }
        }



        /// <summary>
        /// 获取远程文件资源列表
        /// </summary>
        /// <param name="resUri">文件资源列表URL</param>
        /// <returns></returns>
        public List<RemoteFileInfo> GetRemoteFileList(out string message, out int code)
        {
            if (string.IsNullOrEmpty(VideoListAddress))
            {
                code = -3;
                message = "视频服务器地址未配置";
                return null;
            }
            code = 0;
            message = "获取文件成功";
            List<RemoteFileInfo> videoInfoList = null;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(VideoListAddress);
            request.Accept = "application/json,utf-8";
            try
            {
                var response = request.GetResponse();
                using (var s = response.GetResponseStream())
                {
                    using (StreamReader sr = new StreamReader(s))
                    {
                        string jsonString = sr.ReadToEnd();
                        videoInfoList = Newtonsoft.Json.JsonConvert.DeserializeObject<List<RemoteFileInfo>>(jsonString);
                    }

                }

            }
            catch (WebException)
            {
                code = -1;
                message = "网络异常，连接服务器失败";
            }
            catch (Exception)
            {
                code = -2;
                message = "系统异常";
            }
            return videoInfoList;
        }


        /// <summary>
        /// 检查是否配置
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>

        public bool IsConfig(out string message)
        {
            bool result = false;
            if (string.IsNullOrEmpty(VideoCacheFileDirectory))
            {
                message = "视频缓存文件目录未配置";
            }
            else if(!Directory.Exists(VideoCacheFileDirectory))
            {
                message = "视频缓存文件目录不存在";
            }
            else if (string.IsNullOrEmpty(SignalrServerAddress))
            {
                message = "Signalr服务器地址未配置";
            }
            else if (string.IsNullOrEmpty(VideoDownloadAddress))
            {
                message = "视频文件下载地址未配置";
            }
            else if (string.IsNullOrEmpty(VideoListAddress))
            {
                message = "视频列表地址未配置";
            }
            else if(VideoDownPartionSize < 102400)
            {
                message = "视频下载分区大小必须大于于等于100kb";
            }
            else
            {
                result = true;
                message = "";
            }
            return result;
        }


        /// <summary>
        /// 检查是否需要升级
        /// </summary>
        /// <returns></returns>
        public bool IsUpdate()
        {
            string defaultCacheDirectory = VideoCacheFileDirectory;
            string message;
            int code;
            var fileInfos = GetRemoteFileList(out message, out code);
            if (code != 0)
            {
                _MessageProvider.Show(message);
                return false;
            }
            if (fileInfos == null)
            {
                return false;
            }
            foreach (var item in fileInfos)
            {
                string currentFileFullName = Path.Combine(defaultCacheDirectory, item.FileName);
                //检查文件是否存在
                if (File.Exists(currentFileFullName) && (ulong)new FileInfo(currentFileFullName).Length == item.FileSize)
                {
                    continue;
                }
                else
                {
                    return true;
                }
            }
            return false;
        }


        public bool TryUpdate(Form parent,Action uploadCompletedCallback = null)
        {
            if (IsUpdate() && !FileDownloadForm.IsBusy)
            {
                FileDownloadForm.IsBusy = true;
                //var updateForm = new UpdateRemoteFileForm();
                var updateForm = new FileDownloadForm();
                updateForm.FormClosed += (s, arg) =>
                {
                    uploadCompletedCallback?.Invoke();
                    FileDownloadForm.IsBusy = false;
                };
                updateForm.StartPosition = FormStartPosition.CenterParent;
                updateForm.ShowDialog(parent);
                return true;
            }
            return false;
        }
    }
}
